<template>
  <van-button
    v-if="is_followed"
    class="follow-btn"
    round
    size="small"
    :loading='loading'
    @click="onFollow"
  >已关注</van-button>
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading='loading'
    @click="onFollow"
  >关注</van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  model: {
    prop: 'is_followed',
    event: 'update-follow'
  },
  name: 'FollowUser',
  components: {},
  props: {
    is_followed: {
      type: Boolean,
      required: true
    },
    user_id: {
      type: [String, Number, Object],
      required: true
    }
  },
  data () {
    return {
      loading: false
    }
  },
  computed: {},
  watch: {},
  created () { },
  methods: {
    async onFollow () {
      // 开启按钮的 loading 状态
      this.loading = true
      try {
        if (this.is_followed) {
          // 已关注 取消关注
          await deleteFollow(this.user_id)
        } else {
          // 未关注 须关注
          await addFollow(this.user_id)
        }
        // 更新视图
        this.$emit('update-follow', !this.is_followed)
      } catch (err) {
        let message = '操作失败请稍后'
        if (this.response && this.response.status === 400) {
          message = '自己不能关注自己'
        }
        this.$toast(message)
      }
      // 关闭按钮的 loading 状态
      this.loading = false
    }
  }
}
</script>

<style scoped>
</style>
